#include "StdAfx.h"
#include "Rational.h"

NextOnFreeList* Rational::freelist = NULL;

#ifdef _POOL
void* Rational::operator new(size_t size)
{
	if(0 == freelist)
	{
		expandTheFreeList();
	}

	NextOnFreeList* head = freelist;
	freelist = head->next;
	return head;
}

void Rational::operator delete(void* doomed, size_t size)
{
	NextOnFreeList* head = reinterpret_cast<NextOnFreeList*>(doomed);
	head->next = freelist;
	freelist = head;
}
#endif

void Rational::deleteMemPool()
{
	NextOnFreeList* nextPtr;
	for(nextPtr = freelist; nextPtr != NULL; nextPtr = freelist)
	{
		freelist = freelist->next;
		delete[] nextPtr;
	}
}

void Rational::expandTheFreeList()
{
	size_t size = sizeof(Rational) > sizeof(NextOnFreeList*) ? sizeof(Rational) : sizeof(NextOnFreeList*);
	NextOnFreeList* runner = reinterpret_cast<NextOnFreeList*>(new char[size]);
	freelist = runner;
	for(int i = 0; i < EXPANSION_SIZE; ++i)
	{
		runner->next = reinterpret_cast<NextOnFreeList*>(new char[size]);
		runner = runner->next;
	}
	runner->next = 0;
}